<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>部门管理</title>
    <jsp:include page="/common/backend_common.jsp"/>
    <jsp:include page="/common/page.jsp"/>
    <script src="https://cdn.bootcss.com/moment.js/2.18.1/moment-with-locales.min.js"></script>
    <link href="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
    <script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

</head>
<body class="no-skin" youdao="bind" style="background: white; font-size: 12px">
<input id="gritter-light" checked="" type="checkbox" class="ace ace-switch ace-switch-5"/>

<div class="page-header">
    <h1>
        用户管理
        <small>
            <i class="ace-icon fa fa-angle-double-right"></i>
            维护与管理用户关系
        </small>
    </h1>
</div>
<div class="main-content-inner">
    <%--<div class="col-sm-0">--%>
        <%--<div class="table-header">--%>
            <%--分类列表&nbsp;&nbsp;--%>
            <%--<a class="green" href="#">--%>
                <%--<i class="ace-icon fa fa-plus-circle orange bigger-130 dept-add"></i>--%>
            <%--</a>--%>
        <%--</div>--%>
        <%--<div id="deptList">--%>
        <%--</div>--%>
    <%--</div>--%>
    <div class="col-sm-12">
        <div class="col-xs-12">
            <div class="table-header">
                用户列表&nbsp;&nbsp;
                <a class="green" href="#">
                    <i class="ace-icon fa fa-plus-circle orange bigger-130 user-add"></i>
                </a>
            </div>
            <div>
                <div id="dynamic-table_wrapper" class="dataTables_wrapper form-inline no-footer">
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="dataTables_length" id="dynamic-table_length"><label>
                                展示
                                <select id="pageSize" name="dynamic-table_length" aria-controls="dynamic-table" class="form-control input-sm">
                                    <option value="10">10</option>
                                    <option value="25">25</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                </select> 条记录 </label>&nbsp;&nbsp;&nbsp;&nbsp;<label> &nbsp;&nbsp;类型
                                <select id="search-status" name="dynamic-table_length"
                                        aria-controls="dynamic-table" class="form-control input-sm">
                                    <option value="">全部</option>
                                    <option value="0">无效</option>
                                    <option value="1">有效</option>
                                    <option value="2">删除</option>
                                </select></label>
                                <input type="hidden" name="unitDeptId" id="unitDeptId"
                                       value="${sessionScope.user.deptId}"/>
                                &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
                                <input id="search-stUnit" type="search" name="stUnit" style="width: 50%"  class="input-sm" placeholder="请输入要查找的用户" aria-controls="dynamic-table">
                                &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
                                <button class="btn btn-info  fa fa-check research" type="button">
                                    刷新&nbsp;
                                </button>
                            </div>
                        </div>
                    </div>
                    <table id="dynamic-table" class="table table-striped table-bordered table-hover dataTable no-footer" role="grid"
                           aria-describedby="dynamic-table_info" style="font-size:12px">
                        <thead>
                        <tr role="row">
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                姓名
                            </th>
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                所属单位
                            </th>
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                邮箱
                            </th>
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                电话
                            </th>
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                状态
                            </th>
                            <th tabindex="0" aria-controls="dynamic-table" rowspan="1" colspan="1">
                                备注
                            </th>
                            <th class="sorting_disabled" rowspan="1" colspan="1" aria-label=""></th>
                        </tr>
                        </thead>
                        <tbody id="userList"></tbody>
                    </table>
                    <div class="row" id="userPage">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="dialog-dept-form" style="display: none;">
    <form id="deptForm">
        <table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid">
            <tr>
                <td style="width: 80px;"><label for="parentId">上级部门</label></td>
                <td>
                    <select id="parentId" name="parentId" data-placeholder="选择部门" style="width: 200px;"></select>
                    <input type="hidden" name="id" id="deptId"/>
                </td>
            </tr>
            <tr>
                <td><label for="deptName">名称</label></td>
                <td><input type="text" name="name" id="deptName" value="" class="text ui-widget-content ui-corner-all"></td>
            </tr>
            <tr>
                <td><label for="deptSeq">顺序</label></td>
                <td><input type="text" name="seq" id="deptSeq" value="1" class="text ui-widget-content ui-corner-all"></td>
            </tr>
            <tr>
                <td><label for="deptRemark">备注</label></td>
                <td><textarea name="remark" id="deptRemark" class="text ui-widget-content ui-corner-all" rows="3" cols="25"></textarea></td>
            </tr>
        </table>
    </form>
</div>
<div id="dialog-user-form" width="1500px"height="700px" style="display: none; width: 1500px;">
    <form id="userForm">
        <table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid">
            <tr>
               <td><label for="userName">用户名称</label></td>
                <input type="hidden" name="id" id="userId"/>
                <td><input type="text" placeholder="必填" name="username" id="userName" value="" class="text ui-widget-content ui-corner-all"></td>
                <td><label for="userRemark">备注</label></td>
                <td><input type="text"  placeholder="选填" name="remark" id="userRemark" style="width:80%" class="text ui-widget-content ui-corner-all"></td>
            </tr>
            <tr>
                <td><label for="userTelephone">电话</label></td>
                <td><input type="text" placeholder="必填" name="telephone" id="userTelephone" value="" class="text ui-widget-content ui-corner-all"></td>
                <td><label for="userMail">邮箱</label></td>
                <td><input type="text" placeholder="必填" name="mail" id="userMail" value="" class="text ui-widget-content ui-corner-all"></td>
            </tr>
            <tr>
                <td><label for="userPassword">密码</label></td>
                <td><input type="text"  name="password" id="userPassword" value="" class="text ui-widget-content ui-corner-all"></td>
                <td><label for="userStatus">状态</label></td>
                <td>
                    <select id="userStatus" name="status" data-placeholder="选择状态" style="width: 150px;">
                        <option value="1">有效</option>
                        <option value="0">无效</option>
                        <option value="2">删除</option>
                    </select>
                </td>
            </tr>
            <tr>
                <input type="hidden" name="jbzName" id="jbzName" value="${sessionScope.user.jbzName}" >
                <input type="hidden" id="deptSelectId" name="deptId" value="${sessionScope.user.deptId}" >
                <td><label for="userJbzCode">编号</label></td>
                <td><input type="text" name="jbzCode" readonly="true" value="${sessionScope.user.jbzCode}" id="userJbzCode" class="text ui-widget-content ui-corner-all" ></td>
                </tr>

        </table>
    </form>
</div>

<script id="deptListTemplate" type="x-tmpl-mustache">
<ol class="dd-list">
    {{#deptList}}
        <li class="dd-item dd2-item dept-name {{displayClass}}" id="dept_{{id}}" href="javascript:void(0)" data-id="{{id}}">
            <div class="dd2-content" style="cursor:pointer; ">
            {{name}}
            &nbsp;
            <a class="green {{#showDownAngle}}{{/showDownAngle}}" href="#" data-id="{{id}}" >
                <i class="ace-icon fa fa-angle-double-down bigger-120 sub-dept"></i>
            </a>
            <span style="float:right;">
                <a class="green dept-edit" href="#" data-id="{{id}}" >
                    <i class="ace-icon fa fa-pencil bigger-100"></i>
                </a>
                &nbsp;
                <a class="red dept-delete" href="#" data-id="{{id}}" data-name="{{name}}">
                    <i class="ace-icon fa fa-trash-o bigger-100"></i>
                </a>
            </span>
            </div>
        </li>
    {{/deptList}}
</ol>
</script>
<script id="userListTemplate" type="x-tmpl-mustache">
{{#userList}}
<tr role="row" class="user-name odd" data-id="{{id}}"><!--even -->
    <td><a href="#" class="user-edit" data-id="{{id}}">{{username}}</a></td>
    <td>{{jbzName}}</td>
    <td>{{mail}}</td>
    <td>{{telephone}}</td>
    <td>{{#bold}}{{showStatus}}{{/bold}}</td> <!-- 此处套用函数对status做特殊处理 -->
    <td>{{remark}}</td>
    <td>
        <div class="hidden-sm hidden-xs action-buttons">
            <a class="green user-edit" href="#" data-id="{{id}}">
                <i class="ace-icon fa fa-pencil bigger-100"></i>
            </a>
            <a class="red " href="/sys/user/getUserInfo.json?jbzCode={{jbzCode}}&userId={{id}}" data-id="{{id}}" >
                <i class="ace-icon fa fa-flag bigger-100"></i>
            </a>
        </div>
    </td>
</tr>
{{/userList}}
</script>


<script type="application/javascript">
    $(function() {

        var deptList; // 存储树形部门列表
        var deptMap = {}; // 存储map格式的部门信息
        var userMap = {}; // 存储map格式的用户信息
        var optionStr = "";
        var lastClickDeptId = $('#unitDeptId').val();
        var firstLoad = 0;
        var unitDeptId = $('#unitDeptId').val();
        var jbzCode = $('#jbzCode').val();

        var deptListTemplate = $('#deptListTemplate').html();
        Mustache.parse(deptListTemplate);
        var userListTemplate = $('#userListTemplate').html();
        Mustache.parse(userListTemplate);
        // loadDeptTree();
        console.log('得到的单位id'+unitDeptId);
        loadUserList(unitDeptId);

        $(".research").click(function (e) {
            e.preventDefault();
            $("#userPage .pageNo").val('1');
            var name = $("#search-stUnit").val().replace(/\s+/g,"");
            var status = $("#search-status").val();
            loadUserListByname(name,status);

        });

        // $(function () {
        //     $('#datetimepicker1').datetimepicker({
        //         format: 'YYYY-MM-DD',
        //         locale: moment.locale('zh-cn')
        //     });
        // });

        // function loadDeptTree() {
        //     $.ajax({
        //         url: "/sys/dept/tree.json",
        //         success : function (result) {
        //             if (result.ret) {
        //                 deptList = result.data;
        //                 var rendered = Mustache.render(deptListTemplate, {deptList: result.data,
        //                     "showDownAngle": function () {
        //                         return function (text, render) {
        //                             return (this.deptList && this.deptList.length > 0) ? "" : "hidden";
        //                         }
        //                     },
        //                     "displayClass": function () {
        //                         return "";
        //                     }
        //                 });
        //                 $("#deptList").html(rendered);
        //                 recursiveRenderDept(result.data);
        //                 bindDeptClick();
        //                 if(firstLoad == 0){
        //                     loadUserListByname(null,0);
        //                     firstLoad++;
        //                 }
        //             } else {
        //                 showMessage("加载部门列表", result.msg, false);
        //             }
        //         }
        //     })
        // }


        // 递归渲染部门树
        // function recursiveRenderDept(deptList) {
        //     if(deptList && deptList.length > 0) {
        //         $(deptList).each(function (i, dept) {
        //              deptMap[dept.id] = dept;
        //              if (dept.deptList.length > 0) {
        //                  var rendered = Mustache.render(deptListTemplate, {deptList: dept.deptList,
        //                      "showDownAngle": function () {
        //                          return function (text, render) {
        //                              return (this.deptList && this.deptList.length > 0) ? "" : "hidden";
        //                          }
        //                      },
        //                      "displayClass": function () {
        //                          return "hidden";
        //                      }
        //                  });
        //                  $("#dept_" + dept.id).append(rendered);
        //                  recursiveRenderDept(dept.deptList);
        //              }
        //         })
        //     }
        // }

        // 绑定部门点击事件
        // function bindDeptClick() {
        //
        //     $(".sub-dept").click(function (e) {
        //         e.preventDefault();
        //         e.stopPropagation();
        //         $(this).parent().parent().parent().children().children(".dept-name").toggleClass("hidden");
        //         if($(this).is(".fa-angle-double-down")) {
        //             $(this).removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
        //         } else{
        //             $(this).removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
        //         }
        //     });
        //
        //     $(".dept-name").click(function(e) {
        //         e.preventDefault();
        //         e.stopPropagation();
        //         var deptId = $(this).attr("data-id");
        //         handleDepSelected(deptId);
        //     });
        //
        //     $(".dept-delete").click(function (e) {
        //         e.preventDefault();
        //         e.stopPropagation();
        //         var deptId = $(this).attr("data-id");
        //         var deptName = $(this).attr("data-name");
        //         if (confirm("确定要删除部门[" + deptName + "]吗?")) {
        //             $.ajax({
        //                 url: "/sys/dept/delete.json",
        //                 data: {
        //                     id: deptId
        //                 },
        //                 success: function (result) {
        //                     if (result.ret) {
        //                         showMessage("删除部门[" + deptName + "]", "操作成功", true);
        //                         loadDeptTree();
        //                     } else {
        //                         showMessage("删除部门[" + deptName + "]", result.msg, false);
        //                     }
        //                 }
        //             });
        //         }
        //     });
        //
        //     $(".dept-edit").click(function(e) {
        //         e.preventDefault();
        //         e.stopPropagation();
        //         var deptId = $(this).attr("data-id");
        //         $("#dialog-dept-form").dialog({
        //             model: true,
        //             title: "编辑部门",
        //             open: function(event, ui) {
        //                 $(".ui-dialog-titlebar-close", $(this).parent()).hide();
        //                 optionStr = "<option value=\"0\">-</option>";
        //                 recursiveRenderDeptSelect(deptList, 1);
        //                 $("#deptForm")[0].reset();
        //                 $("#parentId").html(optionStr);
        //                 $("#deptId").val(deptId);
        //                 var targetDept = deptMap[deptId];
        //                 if (targetDept) {
        //                     $("#parentId").val(targetDept.parentId);
        //                     $("#deptName").val(targetDept.name);
        //                     $("#deptSeq").val(targetDept.seq);
        //                     $("#deptRemark").val(targetDept.remark);
        //                 }
        //             },
        //             buttons : {
        //                 "更新": function(e) {
        //                     e.preventDefault();
        //                     updateDept(false, function (data) {
        //                         $("#dialog-dept-form").dialog("close");
        //                     }, function (data) {
        //                         showMessage("更新部门", data.msg, false);
        //                     })
        //                 },
        //                 "取消": function () {
        //                     $("#dialog-dept-form").dialog("close");
        //                 }
        //             }
        //         });
        //     })
        // }

        // function handleDepSelected(deptId) {
        //     if (lastClickDeptId != -1) {
        //         var lastDept = $("#dept_" + lastClickDeptId + " .dd2-content:first");
        //         lastDept.removeClass("btn-yellow");
        //         lastDept.removeClass("no-hover");
        //     }
        //     var currentDept = $("#dept_" + deptId + " .dd2-content:first");
        //     currentDept.addClass("btn-yellow");
        //     currentDept.addClass("no-hover");
        //     lastClickDeptId = deptId;
        //     loadUserList(deptId);
        // }


        function loadUserList(deptId) {
            var pageSize = $("#pageSize").val();
            var url = "/sys/user/page.json?deptId=" + deptId;
            var pageNo = $("#userPage .pageNo").val() || 1;
            $.ajax({
                url : url,
                data: {
                    pageSize: pageSize,
                    pageNo: pageNo
                },
                success: function (result) {
                    console.log("返回结果"+JSON.stringify(result))
                    renderUserListAndPage(result, url);
                }
            })
        }

        function loadUserListByname(name,status) {
            var pageSize = $("#pageSize").val();
            var url = "/sys/unit/user/pagebyUsername.json?status="+status;
            var pageNo = $("#userPage .pageNo").val() || 1;
            $.ajax({
                url : url,
                type:"post",
                data: {
                    pageSize: pageSize,
                    pageNo: pageNo,
                    username:name,
                    deptId:unitDeptId,
                },
                success: function (result) {
                    renderUserListAndPage(result, url);
                }
            })
        }

        function renderUserListAndPage(result, url) {
            if (result.ret) {
                if (result.data.total > 0){
                    var rendered = Mustache.render(userListTemplate, {
                        userList: result.data.data,
                        // "showDeptName": function() {
                        //     return deptMap[this.deptId].name;
                        // },
                        "showStatus": function() {
                            return this.status == 1 ? '有效' : (this.status == 0 ? '无效' : '删除');
                        },
                        "bold": function() {
                            return function(text, render) {
                                var status = render(text);
                                if (status == '有效') {
                                    return "<span class='label label-sm label-success'>有效</span>";
                                } else if(status == '无效') {
                                    return "<span class='label label-sm label-warning'>无效</span>";
                                } else {
                                    return "<span class='label'>删除</span>";
                                }
                            }
                        }
                    });
                    $("#userList").html(rendered);
                    bindUserClick();
                    $.each(result.data.data, function(i, user) {
                        userMap[user.id] = user;
                    })
                } else {
                    $("#userList").html('');
                }
                var pageSize = $("#pageSize").val();
                var pageNo = $("#userPage .pageNo").val() || 1;
                console.log(result);
                console.log("result.data.total"+result.data.total+"--"+result.data.data.length);
                console.log("url-----------"+url);
                renderPage(url, result.data.total, pageNo, pageSize, result.data.total > 0 ? result.data.data.length : 0, "userPage", renderUserListAndPage);
            } else {
                showMessage("获取部门下用户列表", result.msg, false);
            }
        }

        $(".user-add").click(function() {
            $("#dialog-user-form").dialog({
                model: true,
                title: "新增用户",
                open: function(event, ui) {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "";
                    // recursiveRenderDeptSelect(deptList, 1);

                    $("#userForm")[0].reset();
                    // $("#deptSelectId").html(optionStr);
                    $("#registerTime").val(new Date("${sessionScope.user.registerTime}").Format("yyyy-MM-dd"));
                    binddeptId();
                },
                buttons : {
                    "添加": function(e) {
                        e.preventDefault();
                        updateUser(true, function (data) {
                            $("#dialog-user-form").dialog("close");
                            //todo 修改为当前单位的用户列表
                            console.log("获取当前单位id"+unitDeptId);
                            loadUserList(unitDeptId);
                            // loadUserList(unitDeptId);
                        }, function (data) {
                            showMessage("新增用户", data.msg, false);
                        })
                    },
                    "取消": function () {
                        $("#dialog-user-form").dialog("close");
                    }
                }
            });
            $(".ui-dialog").css({
                width:"88%",
                "text-align":"center",
                position:"fixed",
                left:"6%",
                top:"10%"
            })
        });
        function binddeptId(){
            $('#deptSelectId').change(function(e) {
                var deptId = $('#deptSelectId').val();
                var dept = deptMap[deptId];
                $('#jbzName').val(dept.name);
                $('#userJbzCode').val(dept.remark);
            })
        };
        function bindUserClick() {
            $(".user-acl").click(function (e) {
                e.preventDefault();
                e.stopPropagation();
                var userId = $(this).attr("data-id");
                $.ajax({
                    url: "/sys/user/acls.json",
                    data: {
                        userId: userId
                    },
                    success: function(result) {
                        if (result.ret) {
                            console.log(result)
                        } else {
                            showMessage("获取用户权限数据", result.msg, false);
                        }
                    }
                })
            });
            $(".user-edit").click(function(e) {
                e.preventDefault();
                e.stopPropagation();
                var userId = $(this).attr("data-id");
                // var registerTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
                // alert(new Date(1553616000000).Format("yyyy-MM-dd hh:mm:ss"));
                $("#dialog-user-form").dialog({
                    model: true,
                    title: "编辑用户"+"(需要修改密码时再填入密码)",
                    open: function(event, ui) {
                        $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                        optionStr = "";
                        recursiveRenderDeptSelect(deptList, 1);
                        $("#userForm")[0].reset();
                        $("#deptSelectId").html(optionStr);
                        binddeptId();
                        var targetUser = userMap[userId];
                        if (targetUser) {
                            $("#deptSelectId").val(targetUser.deptId);
                            $("#userName").val(targetUser.username);
                            $("#userMail").val(targetUser.mail);
                            $("#userTelephone").val(targetUser.telephone);
                            $("#userStatus").val(targetUser.status);
                            $("#userJbzCode").val(targetUser.jbzCode);
                            $("#userRemark").val(targetUser.remark);
                            $("#userId").val(targetUser.id);
                            $("#jbzName").val(targetUser.jbzName);
                            $("#registerTime").val(new Date(targetUser.registerTime).Format("yyyy-MM-dd"));
                        }
                    },
                    buttons : {
                        "更新": function(e) {
                            e.preventDefault();
                            updateUser(false, function (data) {
                                $("#dialog-user-form").dialog("close");
                                if(lastClickDeptId == -1){
                                    loadUserListByname(null,0);
                                    loadNewUserCount();
                                }else{
                                    loadUserList(lastClickDeptId);
                                    loadNewUserCount();
                                }
                            }, function (data) {
                                showMessage("更新用户", data.msg, false);
                            })
                        },
                        "取消": function () {
                            $("#dialog-user-form").dialog("close");
                        }
                    }
                });
                $(".ui-dialog").css({
                    width:"88%",
                    "text-align":"center",
                    position:"fixed",
                    left:"6%",
                    top:"10%"
                })
            });
        }

        $(".dept-add").click(function() {
            $("#dialog-dept-form").dialog({
                model: true,
                title: "新增部门",
                open: function(event, ui) {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide();
                    optionStr = "<option value=\"0\">-</option>";
                    recursiveRenderDeptSelect(deptList, 1);
                    $("#deptForm")[0].reset();
                    $("#parentId").html(optionStr);
                },
                buttons : {
                    "添加": function(e) {
                        e.preventDefault();
                        updateDept(true, function (data) {
                            $("#dialog-dept-form").dialog("close");
                        }, function (data) {
                            showMessage("新增部门", data.msg, false);
                        })
                    },
                    "取消": function () {
                        $("#dialog-dept-form").dialog("close");
                    }
                }
            });
        });

        function recursiveRenderDeptSelect(deptList, level) {
            level = level | 0;
            if (deptList && deptList.length > 0) {
                $(deptList).each(function (i, dept) {
                    deptMap[dept.id] = dept;
                    var blank = "";
                    if (level > 1) {
                        for(var j = 3; j <= level; j++) {
                            blank += "..";
                        }
                        blank += "∟";
                    }
                    optionStr += Mustache.render("<option value='{{id}}'>{{name}}</option>", {id: dept.id, name: blank + dept.name});
                    if (dept.deptList && dept.deptList.length > 0) {
                        recursiveRenderDeptSelect(dept.deptList, level + 1);
                    }
                });
            }
        }

        function updateUser(isCreate, successCallback, failCallback) {
            if(isCreate && $('#userPassword').val() == ''){
                showMessage("新增用户", "新增用户时密码不允许为空", false);
            }else{
            $.ajax({
                url: isCreate ? "/sys/user/save.json" : "/sys/user/update.json",
                data: $("#userForm").serializeArray(),
                type: 'POST',
                success: function(result) {
                    if (result.ret) {
                        // loadDeptTree();
                        if (successCallback) {
                            successCallback(result);
                        }
                    } else {
                        if (failCallback) {
                            failCallback(result);
                        }
                    }
                }
            })
            }
        }

        Date.prototype.Format = function (fmt) { //author: meizz
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };
        var formatJson = function(json, options) {
            if(json == '') return '';
            var reg = null,
                formatted = '',
                pad = 0,
                PADDING = '    '; // one can also use '\t' or a different number of spaces

            // optional settings
            options = options || {};
            // remove newline where '{' or '[' follows ':'
            options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
            // use a space after a colon
            options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;

            // begin formatting...
            if (typeof json !== 'string') {
                // make sure we start with the JSON as a string
                json = JSON.stringify(json);
            } else {
                // is already a string, so parse and re-stringify in order to remove extra whitespace
                json = JSON.parse(json);
                json = JSON.stringify(json);
            }

            // add newline before and after curly braces
            reg = /([\{\}])/g;
            json = json.replace(reg, '\r\n$1\r\n');

            // add newline before and after square brackets
            reg = /([\[\]])/g;
            json = json.replace(reg, '\r\n$1\r\n');

            // add newline after comma
            reg = /(\,)/g;
            json = json.replace(reg, '$1\r\n');

            // remove multiple newlines
            reg = /(\r\n\r\n)/g;
            json = json.replace(reg, '\r\n');

            // remove newlines before commas
            reg = /\r\n\,/g;
            json = json.replace(reg, ',');

            // optional formatting...
            if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                reg = /\:\r\n\{/g;
                json = json.replace(reg, ':{');
                reg = /\:\r\n\[/g;
                json = json.replace(reg, ':[');
            }
            if (options.spaceAfterColon) {
                reg = /\:/g;
                json = json.replace(reg, ': ');
            }

            $.each(json.split('\r\n'), function(index, node) {
                var i = 0,
                    indent = 0,
                    padding = '';

                if (node.match(/\{$/) || node.match(/\[$/)) {
                    indent = 1;
                } else if (node.match(/\}/) || node.match(/\]/)) {
                    if (pad !== 0) {
                        pad -= 1;
                    }
                } else {
                    indent = 0;
                }

                for (i = 0; i < pad; i++) {
                    padding += PADDING;
                }

                formatted += padding + node + '\r\n';
                pad += indent;
            });
            return formatted;
        };

        function updateDept(isCreate, successCallback, failCallback) {
            $.ajax({
                url: isCreate ? "/sys/dept/save.json" : "/sys/dept/update.json",
                data: $("#deptForm").serializeArray(),
                type: 'POST',
                success: function(result) {
                    if (result.ret) {
                        loadDeptTree();
                        if (successCallback) {
                            successCallback(result);
                        }
                    } else {
                        if (failCallback) {
                            failCallback(result);
                        }
                    }
                }
            })
        }
    })
</script>
</body>
</html>
